<?php

class PhotoModel extends SCModel {
	
	public function __construct() {
		parent::__construct();
	}
	
	/**
	 * 
	 * 外链图片（只保存缩略图到服务器，原图使用原始外链）
	 */
	public function linkPhoto() {
		$url = !is_null(SCRequest::post('url')) ? SCRequest::post('url') : die('oops!');
		
		set_time_limit(0);
		
		$attach_path = 'public'.SC_DS.'attach'.SC_DS.date('Y-m');
		CommonFunction::directoryCreate($attach_path);
		$file_new_name = $this->renameFile().'.'.CommonFunction::getFileExtension($url);
		$file_path = SC_APP_PATH.SC_DS.$attach_path; // 图片存储路径
		
	    // 生成缩略图
	    $this->generateThumbnail($url, $file_path.SC_DS.'thumb_'.$file_new_name);	    
	    
	    return json_encode(array(
		    'thumb' => str_replace(SC_DS, '/', $attach_path).'/'.'thumb_'.$file_new_name
	    ));
	}
	
	/**
	 * 删除与指定thing关联的图片记录及缩略图
	 * @param integer $thing_id
	 */
	public function dropPhotoByThingId($thing_id) {
		$photos = $this->from('sc_photo')->where('thing_id = '.$thing_id)->find();
		
		$upload_path = SCConfig::get('UPLOAD_PATH');
		$photos || $photos = array();
		
		foreach($photos as $photo) {
			$thumbs = unserialize($photo->thumbs);
			foreach($thumbs as $thumb) {
				@unlink($upload_path.'/'.$thumb['path']);
			}
			@unlink($upload_path.'/'.$photo->path);
		}
		
		$this->reset()->from('sc_photo')->where('thing_id = '.$thing_id)->delete();
	}
	
	/**
	 * 
	 * 生成缩略图
	 */
	protected function generateThumbnail($soure_img, $dest_img) {
		$Thumb = new Thumbnail(150, 150);
		$Thumb->createThumbnail($soure_img, $dest_img);
	}
} 